import axios from 'axios'
import router from '@/router/index'
import { getToken } from '@/utils/token'
import { ElMessage, ElMessageBox } from 'element-plus'

/* 请求配置 */
const service = axios.create({
    baseURL: import.meta.env.VITE_BASE_URL,
    timeout: 5000,
    headers: {
        'Content-Type': 'application/json; charset=UTF-8'
    },
    validateStatus: function (status) {
        // 200段的都是success状态
        if (status >= 400) {
            let _message
            switch (status) {
                case 400:
                    _message = '请求错误'
                    break
                case 401:
                    _message = '验证失败'
                    window.sessionStorage.clear()
                    router.push('/login').then()
                    break
                case 403:
                    // token过期
                    window.sessionStorage.clear()
                    location.reload()
                    _message = '暂无权限！'
                    break
                case 404:
                    _message = '请求地址出错'
                    break
                case 500:
                    _message = '服务器内部错误！'
                    break
                case 501:
                    _message = '服务未实现'
                    break
                case 502:
                    _message = '网关错误'
                    break
                case 503:
                    _message = '服务不可用'
                    break
                case 504:
                    _message = '网关超时'
                    break
                case 505:
                    _message = 'HTTP版本不受支持'
                    break
                default:
                    _message = '未知错误'
                    break
            }
            ElMessage.error({message: _message, grouping: true})
        }
        return status >= 200 && status < 300
    }
})

// 用于储存正在请求的接口地址
let requestList = []
/* 请求前拦截 */
service.interceptors.request.use(config => {
    // 存在重复的请求，直接取消
    if (requestList.includes(`${config.url}&${config.method}`)) {
        return
    } else {
        requestList.push(`${config.url}&${config.method}`)
    }
    // mock的请求地址为项目启动时的服务地址
    config.baseURL = config.url.substring(0, 5) === '/mock' ? import.meta.env.VITE_MOCK_URL : import.meta.env.VITE_BASE_URL
    config.headers.Authorization = getToken()
    return config
}, error => {
    // 失败时，清空请求队列
    requestList = []
    ElMessage.error({message: '请求超时!'})
    return Promise.reject(error)
})

/* 响应拦截 */
service.interceptors.response.use(response => {
    // 响应结束后 ，清掉requestList里面的url
    requestList = requestList.filter(item => item !== `${response.config.url}&${response.config.method}`)
    const res = response.data
    if (res.code !== 200) {
        if (res.code === 401 || res.code === 403) {  // token失效
            ElMessageBox.confirm(res?.message || 'token失效！').then().finally(() => {
                window.sessionStorage.clear()
                router.push('/login').then()
            })
        } else {
            ElMessage.error({message: res?.message || '系统错误', grouping: true})
        }
        return Promise.reject(new Error('Error'))
    } else {
        return res
    }
}, error => {
    // 失败时，所有请求队列
    requestList = []
    return Promise.reject(error)
})

export default service
